package com.sky.controller.user;

import com.sky.constant.RedisConstant;
import com.sky.entity.Category;
import com.sky.result.Result;
import com.sky.service.CategoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user/category")
@Api(tags = "C端-分类接口")
public class CategoryUserController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询分类
     *
     * @param type
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("查询分类")
    public Result<List<Category>> list(Integer type) {
        //先去查redis缓存
        List<Category> categories = redisTemplate.opsForList().range(RedisConstant.HOME_CATEGORY, RedisConstant.START, RedisConstant.END);
        if (categories != null && categories.size() > 0) {
            System.out.println("查询的是redis缓存下的分类");
            return Result.success(categories);
        }
        //缓存为空,查询数据库
        List<Category> list = categoryService.list(type);
        System.out.println("查询数据库的分类");
        redisTemplate.opsForList().rightPushAll(RedisConstant.HOME_CATEGORY, list);
        //设置时间
        redisTemplate.expire(RedisConstant.HOME_CATEGORY, 60l, TimeUnit.SECONDS);
        return Result.success(list);
    }
}